"""
InCloud MCP Server main implementation
"""
from fastmcp import FastMCP
import click
import logging
import os
from typing import List, Dict, Any

from .config import load_config, get_config
from .swagger.tool_generator import ToolGenerator
from .tools.common_tools import tools as common_tools, set_custom_service_list
from .logging_config import setup_logging, configure_third_party_loggers

logger = logging.getLogger(__name__)


@click.command()
@click.option(
    "--config",
    type=click.Path(exists=True),
    default="config.yaml",
    help="Path to configuration file",
)
@click.option(
    "--transport",
    type=click.Choice(["stdio", "sse", "streamable-http"]),
    default="sse",
    help="Transport type",
)
@click.option(
    "--port",
    type=int,
    default=8000,
    help="Port number for HTTP transport",
)
@click.option(
    "--host",
    type=str,
    default="127.0.0.1",
    help="Host address for HTTP transport",
)
@click.option(
    "--services",
    type=str,
    default=None,
    help="Comma-separated list of services to enable (overrides config)",
)
@click.option(
    "--log-level",
    type=click.Choice(["DEBUG", "INFO", "WARNING", "ERROR"]),
    default="INFO",
    help="Logging level",
)
@click.option(
    "--log-file",
    type=str,
    default=None,
    help="Log file name (auto-generated if not specified)",
)
@click.option(
    "--log-dir",
    type=str,
    default="logs",
    help="Directory for log files",
)
def main(
    config: str,
    transport: str,
    port: int,
    host: str,
    services: str,
    log_level: str,
    log_file: str,
    log_dir: str
):
    """InCloud MCP Server - Swagger-based API tool registration"""

    # Setup enhanced logging
    log_file_path = setup_logging(
        log_level=log_level,
        log_file=log_file,
        log_dir=log_dir,
        console_output=True
    )

    # Configure third-party loggers
    configure_third_party_loggers()
    
    try:
        logger.info("=" * 60)
        logger.info("🚀 Starting InCloud MCP Server")
        logger.info("=" * 60)
        logger.info(f"📋 Configuration file: {config}")
        logger.info(f"📊 Log level: {log_level}")
        logger.info(f"📁 Log file: {log_file_path}")
        logger.info(f"🌐 Transport: {transport}")
        logger.info(f"🔌 Host: {host}:{port}")

        # Load configuration
        if not os.path.exists(config):
            logger.error(f"Configuration file not found: {config}")
            raise click.ClickException(f"Configuration file not found: {config}")

        app_config = load_config(config)
        logger.info(f"✅ Configuration loaded successfully")
        logger.info(f"🔗 Swagger base URL: {app_config.swagger.base_url}")
        logger.info(f"⏱️  Request timeout: {app_config.swagger.timeout}s")

        # Override services if specified via command line
        if services:
            service_list = [s.strip() for s in services.split(",")]
            # Filter config to only include specified services
            filtered_services = {}
            for service_name in service_list:
                if service_name in app_config.services:
                    filtered_services[service_name] = app_config.services[service_name]
                else:
                    logger.warning(f"Service {service_name} not found in configuration")
            app_config.services = filtered_services
            logger.info(f"🔧 Filtered services to: {service_list}")

        # Log enabled services
        enabled_services = app_config.get_enabled_services()
        logger.info(f"🛠️  Enabled services ({len(enabled_services)}): {list(enabled_services.keys())}")
        
        # Create MCP server
        mcp = FastMCP(
            name="incloud-mcp-server",
            port=port,
            host=host,
            stateless_http=True
        )
        
        # Register common tools
        logger.info("Registering common tools...")
        for tool in common_tools:
            mcp.tool(tool)
        
        # Set up custom service list for prompt understanding
        enabled_services = app_config.get_enabled_services()
        service_list = [(name, f"InCloud {name.title()} Service") for name in enabled_services.keys()]
        set_custom_service_list(service_list)
        
        # Generate and register dynamic tools
        logger.info("Generating dynamic tools from Swagger documentation...")
        tool_generator = ToolGenerator(app_config)
        
        total_tools_registered = 0
        for service_name in enabled_services.keys():
            logger.info(f"Generating tools for service: {service_name}")
            try:
                service_tools = tool_generator.generate_service_tools(service_name)
                
                for tool_func in service_tools:
                    mcp.tool(tool_func)
                    total_tools_registered += 1
                    logger.debug(f"Registered tool: {tool_func.__name__}")
                
                logger.info(f"Registered {len(service_tools)} tools for service {service_name}")
                
            except Exception as e:
                logger.error(f"Failed to generate tools for service {service_name}: {e}")
                continue
        
        logger.info(f"Successfully registered {total_tools_registered} dynamic tools")
        logger.info(f"Total tools available: {total_tools_registered + len(common_tools)}")
        
        # Start the server
        logger.info(f"Starting InCloud MCP Server on {transport} transport")
        if transport in ["sse", "streamable-http"]:
            logger.info(f"Server will be available at http://{host}:{port}")
        
        mcp.run(transport=transport)
        
    except Exception as e:
        logger.error(f"Failed to start server: {e}")
        raise click.ClickException(str(e))


def create_sample_config():
    """Create a sample configuration file"""
    sample_config = """swagger:
  base_url: "http://10.180.210.99:30079"
  timeout: 30

services:
  icompute:
    enabled: true
    apis:
      - method: "GET"
        path: "/v1/vhosts"
        description: "List virtual hosts"
        enabled: true
      - method: "POST"
        path: "/v1/vhosts"
        description: "Create virtual host"
        enabled: true
      - method: "GET"
        path: "/v1/vhosts/{id}"
        description: "Get virtual host details"
        enabled: true

  istorage:
    enabled: true
    apis:
      - method: "GET"
        path: "/v1/volumes"
        description: "List storage volumes"
        enabled: true
      - method: "POST"
        path: "/v1/volumes"
        description: "Create storage volume"
        enabled: true

  inetwork:
    enabled: false
    apis: []

  imonitor:
    enabled: false
    apis: []

  isecurity:
    enabled: false
    apis: []

# Optional authentication
auth:
  type: "bearer"  # bearer, basic, api_key
  token: "your-token-here"
  # For basic auth:
  # username: "your-username"
  # password: "your-password"
  # For API key:
  # api_key: "your-api-key"
  # api_key_header: "X-API-Key"
"""
    
    with open("config.yaml", "w", encoding="utf-8") as f:
        f.write(sample_config)
    
    print("Sample configuration file created: config.yaml")
    print("Please edit the configuration file to match your InCloud setup.")


@click.command()
def init():
    """Initialize InCloud MCP Server with sample configuration"""
    if os.path.exists("config.yaml"):
        if not click.confirm("config.yaml already exists. Overwrite?"):
            return
    
    create_sample_config()


@click.group()
def cli():
    """InCloud MCP Server CLI"""
    pass


cli.add_command(main, name="run")
cli.add_command(init)


if __name__ == "__main__":
    main()
